package servlet;

import util.ParameterUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * @author 石小俊
 */
@WebServlet("/modifyEmp")
public class ModifyEmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求字符集
        req.setCharacterEncoding("utf-8");
        // 获取请求参数
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String salary = req.getParameter("salary");
        String gender = req.getParameter("gender");
        String edu = req.getParameter("edu");
        String[] hobbies = req.getParameterValues("hobbies");

        // JDBC实现修改操作
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 根据主键查询员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?, ")
                    .append("   salary = ?, ")
                    .append("   gender = ?, ")
                    .append("   edu = ?, ")
                    .append("   hobbies = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, ParameterUtil.arrayToString(hobbies));
            ps.setInt(6, Integer.parseInt(id));

            ps.executeUpdate();

            // 重定向到员工列表
            resp.sendRedirect("findAll");

        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到驱动");
        } catch (SQLException e) {
            throw new RuntimeException("数据访问异常");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放连接失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放状态集失败");
                }
            }
        }
    }
}
